<?php


namespace app\common\cachemodel;


use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

class ZlRecommendDivination extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_recommend_divination';

    protected $cacheModel = 'divination.recommend_question';

    /**
     * 牌阵 阵型信息  1=>【3牌阵】 2=>【四牌阵(上二下二)】 3=>【四牌阵（上一下三）】
     * @var array
     */
    public $tarotTypeFlag = [
        1 => 1, // 1号牌阵（免费）
        2 => 1, // 2号牌阵（感情发展）
        3 => 2, // 3号牌阵（桃花运势）
        4 => 3, // 4号牌阵（分手复合）
    ];

    /**
     * 获取推荐问题
     * @param int $type
     * @param int $dataType 返回数据格式 1=>旧版本结构 2=>新版本【塔罗和占卜数据结构相同】
     * @return array
     * @throws \think\exception\DbException
     */
    public function getRecommendQuestion(int $type = 1, int $dataType = 1): array
    {
        $data = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $type)
            ->setPage(-1)
            ->setSort('desc')
            ->getListPage(function ($ids = [], $isCache = true, $sortType = 'desc') use ($type)
            {
                if ($isCache)
                { // 开启了缓存
                    return $this->getInfoByIdsInData($ids, [$type], $sortType);
                } else
                { // 没开启缓存
                    return $this->getPaginateInData([$type], $sortType);
                }
            }, 'sort', [], 0);

        return $this->recommendQuestionReset($type, $data['data'], $dataType);
    }

    /**
     * @param int $type 1=>骰子问题 2=>塔罗问题
     * @param array $data
     * @param int $dataType
     * @return array
     * @throws \Exception
     */
    private function recommendQuestionReset(int $type, array $data,int $dataType): array
    {
        $resData = [];

        if ($type === 1 || $dataType === 2)
        {
            foreach ($data as $item)
            {
                $resData[] = [
                    'id' => (int)$item['id'],
                    'question' => $item['question'],
                    'type' => $type,
                ];
            }
        } else
        {
            $tarotConfig = config('tarot.tarot_type');
            $tarotRecordModel = (new ZlTarotRecords());
            foreach ($data as $item)
            {
                $tipList = [];
                foreach ($tarotConfig[$item['tarot_type']] as $tarotTypeItem)
                {
                    $tipList[] = $tarotTypeItem['tip'];
                }
                $divinationNum = $tarotRecordModel->getDivinationNum($item['tarot_type']);
                $divinationNum += $item['base_num'];
                $resData[] = [
                    'id' => (int)$item['id'],
                    'img' => $item['img'],
                    'question' => $item['question'],
                    'desc' => $item['desc'],
                    'flag' => $this->tarotTypeFlag[$item['tarot_type']],
                    'num' => "已有{$divinationNum}人测试", // 已下单数 基数+ 下单数
                    'type' => $type,    // 1=>骰子问题 2=>塔罗问题
                    'tip_list' => $tipList
                ];
            }
        }
        return $resData;
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('id', $ids);
            } else
            {
                $this->where(['type' => $type[0], 'status' => 1]);
            }

            return $this->order('sort ' . $sortType)->column('img,question,desc,type,tarot_type,gid,base_num,sort', 'id');
        }
        catch (\Exception $e)
        {
            Log::write('获取推荐问题错误：' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」");
            return [];
        }
    }

    /**
     * 缓存关闭
     * @param array $type
     * @param string $sortType
     * @return array|void
     * @throws \think\exception\DbException
     */
    public function getPaginateInData($type, $sortType)
    {
        return $this->where(['type' => $type[0], 'status' => 1])
            ->order('sort ' . $sortType)
            ->field('id,img,question,desc,type,tarot_type,gid,base_num,sort')
            ->paginate(1000)->toArray();
    }

}
